(function($ui) {

    /*对话框堆栈，用于存储多重调用的对话框，并用另一个堆栈存储对话框确认按钮时的js代码*/
    //$ui.dialogWindow = [];
    //$ui.dialogConfirm = [];
    $ui.dialogInfo = [];

    function $am(el) {
        el = el.indexOf("#") == -1 ? "#" + el : el;
        return $(el).get(0);
    }
	
	/**
     * Get current dialog window "id".
     ```
     $.ui.getDialogId();
     ```
     * @title $.ui.getDialogId();
     */
	$ui.getDialogId = function(){
		if(this.dialogInfo.length > 0){
		  var id = "dialog_level_" + (this.dialogInfo.length);
		  return id;
		}
		return null;
	}

    /**
     * Get inside element of the dialog window By it's "id" attribute.
     ```
     $.ui.getDialogElementById("myDivID");
     ```
	 * @param {String|id} element to find
     * @title $.ui.getDialogElementById();
     */
    $ui.getDialogElementById = function(id) {
        if(this.dialogInfo.length > 0) {
            var dialog = this.dialogInfo[this.dialogInfo.length - 1];
			var dialogDiv = dialog['dialogWindow'];
			if($(dialogDiv)){
				var jqObj = $(dialogDiv).find("[id='" + id + "']");
				if(jqObj){
            		return jqObj.get(0);
				}
			}
        }
        return null;
    }

    $ui.createDialog = function(content, confirmScript, title) {
        var that = this;
        var id = "dialog_level_" + (this.dialogInfo.length + 1);
        var xmlhttp = new XMLHttpRequest();
        var dialogDiv = document.createElement("div");
        dialogDiv.className = "jQui_dialog";
        dialogDiv.id = id;
        dialogDiv.appendChild($("<div class='dialogContainer'></div>").get());
        that.viewportContainer.append(dialogDiv);

        //如果还没有蒙板,添加一个蒙板
        if(that.dialogInfo.length == 0) {
            var maskDiv = document.createElement("div");
            maskDiv.id = "jq_dialog_mask";
            maskDiv.setAttribute('style', "position:absolute;top:0px;left:0px;right:0px;bottom:0px;z-index:9998;background:rgba(0,0,0,.4)");
            that.viewportContainer.append(maskDiv);
        }

        //添加头部
        var dialog_headerBar = "<div class='dialogheader' ><a href='javascript:;' data-ignore='true' onclick='$.ui.closeDialog();'><div class='item icon_close'></div></a>" + "<div class='item flex'><h1>" + title + "</h1></div><a href='javascript:;'  data-ignore='true' onclick='$.ui.confirmDialog();'><div class='item icon_sure'></div></a></div>";
        $("#" + id + " .dialogContainer").html(dialog_headerBar + content);

        //添加内容
        //$("#"+id+" .dialogContainer").append();
        dialogDiv.style.display = "block";

        that.scrollingDivs[id + "_dialogContainer"] = $("#" + id + " .dialogContainer").scroller({
            scrollBars : true,
            vertical : true,
            vScrollCSS : "jqmScrollbar"
        });

        that.dialogInfo.push({
            dialogWindow : dialogDiv,
            dialogConfirm : confirmScript
        });
        //that.dialogConfirm.push(confirmScript);
        button = null;
        content = null;
        that.scrollingDivs[id + "_dialogContainer"].initEvents();
        that.scrollToTop('dialog');
    }
    /**
     * Load a content panel in a dialog window.  We set the innerHTML so event binding will not work.
     ```
     $.ui.openDialog("#myDiv","通讯录","alert('拿到通讯录了！');");
     ```
     * @param {String|id} panel to show
     * @param {String|confirmScript functionName} 确认时执行的js代码串
     * @param {String|title} 标题
     * @title $.ui.openDialog();
     * @api hundsun
     */
    $ui.openDialog = function(href, title, confirmScript) {
        var params = [];
        var argLen = arguments.length;
        if(argLen > 3) {
            params = Array.prototype.slice.call(arguments, 3);
        }

        var that = this;
        
        //如果还没有蒙板,添加一个蒙板
        if(that.dialogInfo.length == 0) {
            var maskDiv = document.createElement("div");
            maskDiv.id = "jq_dialog_mask";
            maskDiv.setAttribute('style', "position:absolute;top:0px;left:0px;right:0px;bottom:0px;z-index:9998;background:rgba(0,0,0,.4)");
            that.viewportContainer.append(maskDiv);
        }
        this.showMask();
        
        var id = "dialog_level_" + (this.dialogInfo.length + 1);
        var xmlhttp = new XMLHttpRequest();

        var xmlHttpTimeout = setTimeout(function (){
            xmlHttp.abort();
            that.hideMask();
            $("#jq_dialog_mask").remove();
            alert("Request timed out");
         },25000);
        
        
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            	clearTimeout(xmlHttpTimeout); 
                //新建一个dialog div;
                var dialogDiv = document.createElement("div");
                dialogDiv.className = "jQui_dialog";
                dialogDiv.id = id;
                $(dialogDiv).css("z-index",9999 + that.dialogInfo.length);
                //添加头部
                var dialog_struts = "<div class='dialogheader' ><a href='javascript:;' onclick='$.ui.closeDialog();'><div class='item icon_close'></div></a>" + "<div class='item flex'><h1>" + title
				 + "</h1></div><a href='javascript:;' onclick='$.ui.confirmDialog();'><div class='item icon_sure'></div></a></div><div class='dialogContainer'><div class='dialogcontent'></div></div>";
				dialogDiv.innerHTML = dialog_struts;
				
                that.viewportContainer.append(dialogDiv);
				
				
                $("#" + id + " .dialogContainer .dialogcontent").html(xmlhttp.responseText);

                //添加内容
                //$("#"+id+" .dialogContainer").append();
                dialogDiv.style.display = "block";

                that.scrollingDivs[id + "_dialogContainer"] = $("#" + id + " .dialogContainer .dialogcontent").scroller({
                    scrollBars : true,
                    vertical : true,
                    vScrollCSS : "jqmScrollbar"
                });

                that.dialogInfo.push({
                    dialogWindow : dialogDiv,
                    dialogConfirm : confirmScript,
                    dialogLoadingParams : params
                });
                button = null;
                content = null;
                that.scrollingDivs[id + "_dialogContainer"].initEvents();
                that.scrollToTop('dialog');
                that.parseScriptTags(dialogDiv);
                dialogDiv = null;
                that.hideMask();
            }
        };
        //ajaxUrl = target;
        var newtarget = this.useAjaxCacheBuster ? href + (href.split('?')[1] ? '&' : '?') + "cache=" + Math.random() * 10000000000000000 : href;
        xmlhttp.open("GET", newtarget, true);
        xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xmlhttp.send();

    }
    /**
     * Hide the dialog window and remove the content
     ```
     $.ui.closeDialog("#myDiv");
     ```
     * @title $.ui.closeDialog();
     */
    $ui.closeDialog = function() {
        //$am("dialogContainer").innerHTML = "";
        //$am("jQui_dialog").style.display = "none";

        var id = "dialog_level_" + this.dialogInfo.length;
        this.scrollingDivs[id + '_dialogContainer'].removeEvents();
        this.scrollingDivs[id + '_dialogContainer'] = undefined;
        var dialog = this.dialogInfo.pop();
        $(dialog.dialogWindow).remove();

        if(this.dialogInfo.length == 0) {
            $("#jq_dialog_mask").remove();
        }

        if(typeof MawNumberInputMethod != 'undefined'){
					MawNumberInputMethod.hide();        	
        }
    }
    /**
     * Remove all the dialog window and remove the content
     ```
     $.ui.closeAllDialog();
     ```
     * @title $.ui.closeAllDialog();
     */
    $ui.closeAllDialog = function() {
        while(this.dialogInfo.length > 0) {
            var id = "dialog_level_" + this.dialogInfo.length;
            this.scrollingDivs[id + '_dialogContainer'].removeEvents();
            this.scrollingDivs[id + '_dialogContainer'] = undefined;
            var dialog = this.dialogInfo.pop();
            $(dialog.dialogWindow).remove();

            if(this.dialogInfo.length == 0) {
                $("#jq_dialog_mask").remove();
            }
        }
        if(typeof MawNumberInputMethod !== 'undefined'){
					MawNumberInputMethod.hide();        	
        }
    }
    /**
     * Hide the dialog window and remove the content
     ```
     $.ui.closeDialog("#myDiv");
     ```
     * @title $.ui.closeDialog();
     */
    $ui.confirmDialog = function() {

        var id = "dialog_level_" + this.dialogInfo.length;
        this.scrollingDivs[id + "_dialogContainer"].removeEvents();
        this.scrollingDivs[id + '_dialogContainer'] = undefined;

        var dialog = this.dialogInfo.pop();

        var confirmScript = dialog.dialogConfirm;
        if( typeof confirmScript == 'function') {
            var params = dialog.dialogConfirmParams;
            confirmScript.apply(null, params);
        } else {
            window.eval(confirmScript);
        }
        $(dialog.dialogWindow).remove();

        if(this.dialogInfo.length == 0) {
            $("#jq_dialog_mask").remove();
        }
        if(typeof MawNumberInputMethod !== "undefined"){
			MawNumberInputMethod.hide();        	
        }
    }

    $ui.setConfirmParams = function(params) {
        if(this.dialogInfo.length > 0) {
            this.dialogInfo[this.dialogInfo.length - 1].dialogConfirmParams = params;
        }
    }

    $ui.getLoadingParams = function() {
        if(this.dialogInfo.length > 0) {
            return this.dialogInfo[this.dialogInfo.length - 1].dialogLoadingParams;
        }
        return null;
    }
})($.ui);
